﻿using NLog;
using StackExchange.Redis;
using System.Data;
using System.DirectoryServices.ActiveDirectory;
using TeachlyQBank.DbPool;
using TeachlyQBank.Models;

namespace TeachlyQBank.DbServer
{
    public class PermissionServer
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly MySqlConnectionAdapter _mysql; // 操作mysql的类
        private readonly IConnectionMultiplexer _redis;  // 操作redis的类
        private readonly Logger _logger;  //记录日志的类

        // 完成依赖注入
        public PermissionServer(MySqlConnectionAdapter mysql, IConnectionMultiplexer redis, IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _redis = redis;
            _logger = LogManager.GetCurrentClassLogger();
            _mysql = mysql;
        }

        //功能: 查询所有的用户角色信息
        //返回:查询成功返回一个List<Permission>包含目标信息，失败返回null
        public List<Permission> SelAllPermission()
        {
            List<Permission> resultList = new List<Permission>();

            _mysql.Open();

            string query = "SELECT * FROM T_PERMISSION ";

            DataSet data = _mysql.ExecuteQuery(query);

            if (data == null || data.Tables[0].Rows.Count == 0)
            {
                _mysql.Close();
                // 查询出先错误
                _logger.Error($"查询出错,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                return null;
            }
            else
            {
                foreach (DataRow row in data.Tables[0].Rows)
                {
                    Permission permission = new Permission();

                    permission.permission_id = row["permission_id"].ToString();
                    permission.permission_name = row["permission_name"].ToString();
                    permission.description = row["description"].ToString();
                    permission.resource = row["resource"].ToString();
                    permission.action = row["action"].ToString();
                    permission.domain = row["domain"].ToString();

                    resultList.Add(permission);
                }
                _mysql.Close();

                return resultList;
            }
        }

        //功能: 根据传递过来的Permission修改系统的权限
        //参数:一个Permission里面包含了要修改的内容
        //返回:数据库影响的条数成功返回1，失败返回-1
        public int UpdatePermission(Permission permission)
        {
            _mysql.Open();
            string query = "UPDATE T_PERMISSION SET permission_name=@permission_name,description=@description,resource=@resource,action=@action,domain=@domain  where permission_id=@permission_id;";
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"@permission_id",permission.permission_id !},
                { "@permission_name",permission.permission_name !},
                { "@description",permission.description !},
                {"@resource",permission.description ! },
                { "@action",permission.action !},
                {"@domain",permission.domain ! }

            };
            int count = _mysql.ExecuteNonQuery(query, parameters);
            if (count > 0)
            {
                _logger.Info($"修改了一个用户:{permission.permission_name}的角色,用户ID:{permission.permission_id},本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"修改用户角色出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }


        // 功能:添加一个系统权限到数据库
        // 参数:一个系统权限的结构题代表知识点信息
        // 返回:执行成功返回数据库影响条数1,执行失败返回-1
        public int AddPermission(Permission permission)
        {
            _mysql.Open();



            string query = "insert into T_PERMISSION(permission_id,permission_name,description,resource,action,domain) " +
            "values(@permission_id,@permission_name,@description,@resource,@action,@domain)";


            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { "@permission_id", permission.permission_id! },
                { "@permission_name",permission.permission_name!},
                { "@description",permission.description!},
                { "@resource",permission.resource!},
                { "@action",permission.action!},
                { "@domain",permission.domain! }

            };

            int count = _mysql.ExecuteNonQuery(query, parameters);

            if (count > 0)
            {
                _logger.Info($"添加了一个新的系统权限:{permission.permission_name},本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"添加系统权限出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }

        // 功能:根据一个用户的账号删除一个用户
        // 参数:传入一个course里面包含了要删除课程的ID
        // 返回:执行成分返回数据库影响的条数1,失败返回-1
        public int DelPermissionServer(Permission permission)
        {
            _mysql.Open();
            string query = "DELETE FROM T_PERMISSION WHERE permission_id=@permission_id";
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"@permission_id",permission.permission_id !}
            };
            int count = _mysql.ExecuteNonQuery(query, parameters);
            if (count > 0)
            {
                _logger.Info($"删除了一个系统权限ID:{permission.permission_id},本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"删除系统权限出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }

    }
}
